package com.yejhxt.receive;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.yejhxt.inter.deviceMapper;
import com.yejhxt.inter.messageMapper;
import com.yejhxt.inter.roleMapper;
import com.yejhxt.inter.sosMapper;
import com.yejhxt.model.device;
import com.yejhxt.model.message;
import com.yejhxt.model.role;
import com.yejhxt.model.sos;
	
public class receive {
	 private static SqlSessionFactory sqlSessionFactory;
	    private static Reader reader; 
	
	    static{
	        try{
	            reader    = Resources.getResourceAsReader("Configuration.xml");
	            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

	        }catch(Exception e){
	            e.printStackTrace();
	        }
	    }

	    public static BlockingQueue<message> bqmessage=new LinkedBlockingQueue<message> ();
	    public static BlockingQueue<sos> bqsos=new LinkedBlockingQueue<sos> ();
	    public static   ExecutorService cachedThreadPool;
	    public static ServerSocket  SocketServer;
	    public static  Thread thread1,thread2;
public static void init(){
	cachedThreadPool = Executors.newCachedThreadPool();  
	try {
		SocketServer=new ServerSocket (1080);
		System.out.println("开始监听1080端口");
		Socket socket;
		thread1=new Thread(new SaveThread());
		thread2=new Thread(new SaveSosThread());
		cachedThreadPool.execute(thread1);
		cachedThreadPool.execute(thread2);
		while((socket=SocketServer.accept())!=null){
			System.out.println(socket.getRemoteSocketAddress()+"设备链接");
			cachedThreadPool.execute(new Thread(new ReceiveThread(socket)));
		}
		
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	finally {
		try {
			if(SocketServer!=null)
			SocketServer.close();
			if(cachedThreadPool!=null)
				cachedThreadPool.shutdown();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
public static void shutdown(){
	if(cachedThreadPool!=null)
	{
		cachedThreadPool.shutdown();
	}
	if(SocketServer!=null)
	{
		try {
			SocketServer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}

 static class ReceiveThread implements Runnable{
  public Socket mSocket;
  public InputStreamReader InputStreamReader;
  public OutputStreamWriter OutputStreamWriter;
 public  ReceiveThread(Socket mSocket ){
	 
	 System.out.println("创建了新的接收线程");
	  if(mSocket==null)
		  return;
	  if(mSocket.isClosed())
		  return;
	  this.mSocket=mSocket;
	  try {
		InputStreamReader=new InputStreamReader(mSocket.getInputStream());
	    OutputStreamWriter =new OutputStreamWriter(mSocket.getOutputStream());
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
   
  }
  
	@Override
	public void run() {
		  if(mSocket==null)
			  return;
		  if(mSocket.isClosed())
			  return;
		  
		  char[] b=new char[50];
		  
		  int t=0;
		  try {
			while((t=InputStreamReader.read(b))!=-1){
				
				String str=new String(b);
				str=str.trim();
				System.out.println("接收数据"+str);
			if(StringUtils.startsWith(str, "*"))
			{
				if(StringUtils.endsWith(str, "#"))
				{
					str=StringUtils.substring(str, 1, str.length()-1);
					String[] strs=StringUtils.split(str, "&");
					if(strs==null)
						continue;
					if(strs.length!=3)
						continue;
					
					
					message m=new message();
					Date now=new Date();
					m.setCreatetime(now);
					m.setHappendtime (now);
					m.setModifytime(now);
					m.setDevicecoder(strs[0]);
                    m.setLongtitude(Float.parseFloat(strs[1]));
                    m.setLatitude(Float.parseFloat(strs[2]));
                    bqmessage.put(m);
				}
				
			}
			
			if(StringUtils.startsWith(str, "!"))
			{
				if(StringUtils.endsWith(str, "#"))
				{
					str=StringUtils.substring(str, 1, str.length()-1);
					String[] strs=StringUtils.split(str, "&");
					if(strs==null)
						continue;
					if(strs.length!=3)
						continue;
					sos sos=new sos();
					Date now=new Date();
					sos.setCreatetime(now);
					sos.setHappendtime (now);
					sos.setModifytime(now);
					sos.setDevicecoder(strs[0]);
					//sos.setDeviceid(Long.parseLong());	
					sos.setLongtitude(Float.parseFloat(strs[1]));
					sos.setLatitude(Float.parseFloat(strs[2]));
                    bqsos.put(sos);
				}
			}
				
				
			  }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  finally {
			  try {
			if(InputStreamReader!=null)
			{
				
					InputStreamReader.close();
				
			}
			if(OutputStreamWriter!=null)
			{
				OutputStreamWriter.close();
			}
			if(mSocket!=null)
			{
				mSocket.close();
			}
			  } catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		
	}
	 
	 
	 
 } 


 static class SaveThread implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		message message=null;
	
		try {
			while((message=bqmessage.take())!=null){
				System.out.println("save message");
				SqlSession session = sqlSessionFactory.openSession();

				messageMapper messageMapper=session.getMapper(messageMapper.class);

				deviceMapper deviceMapper=session.getMapper(deviceMapper.class);
				roleMapper roleMapper=session.getMapper(roleMapper.class);
				device device=deviceMapper.selectBydevcoder(message.getDevicecoder());
				System.out.println("search message"+message.getDevicecoder());
				if(device==null)
					continue;
				
				System.out.println("save message"+message.getDevicecoder());
				message.setDeviceid(device.getDeviceid());
				messageMapper.insert(message);
			
				session.commit();
				session.close();
				message=null;
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	 
	 
	 
 } 
 
 
 static class SaveSosThread implements Runnable{

	@Override
	public void run() {
	sos sos=null;
	try {
		while((sos=bqsos.take())!=null){
			
			SqlSession session = sqlSessionFactory.openSession();

			sosMapper sosMapper=session.getMapper(sosMapper.class);
			deviceMapper deviceMapper=session.getMapper(deviceMapper.class);
			roleMapper roleMapper=session.getMapper(roleMapper.class);
			device device=deviceMapper.selectBydevcoder(sos.getDevicecoder());
	
			
			System.out.println("search message"+sos.getDevicecoder());
			if(device==null)
				continue;
			role role=roleMapper.selectByPrimaryKey(device.getRoleid());
			if(role==null)
				continue;
			sos.setStatus(1);
			sos.setRoleid(role.getRoleid());
			sos.setDeviceid(device.getDeviceid());
			sosMapper.insert(sos);
			session.commit();
			session.close();
			sos=null;
		}
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
	}
	 
	 
	 
 } 
public static void main(String arg[]){
   init();
	
}
	
	
}
